<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<p>请将此文件拖拽到Chrome中打开，并按F12打开调试窗口，Console中查看结果</p>
<script type="text/javascript">

    // js二进制操作可参考 https://my.oschina.net/appnet/blog/1647923
    window.onload = function () {

        console.log("hello")

        let ws = new WebSocket("ws://127.0.0.1:18802/echo");
        ws.binaryType = "arraybuffer";

        ws.onopen = function(evt) {
            console.log("Connection open ...");

            let msgBody = {
                Msg: "鲍勃",
                Value: 331,
            }

            // 消息体编码
            // 注意：需要对字符串做url编码， 否则中文乱码。该问题仅限于json传输模式
            // cellnet接收时，必须使用wsjson编码处理
            let msgData = JSON.stringify(msgBody)

            let encoder = new TextEncoder('utf8')
            let jsonBody= encoder.encode( msgData)

            // TODO 实现消息ID与消息体绑定
            let msgid = 1234

            let pkt = new ArrayBuffer( 2+ jsonBody.length)
            let dv = new DataView(pkt)

            // 写入消息号
            dv.setUint16(0, msgid, true)

            // 这里body使用的是Json编码
            for(let i = 0;i <jsonBody.length;i++){
                dv.setUint8(2+i, jsonBody[i])
            }

            // 发送
            ws.send(pkt);
        };

        ws.onmessage = function(evt) {

            if (evt.data instanceof ArrayBuffer ){

                let dv = new DataView(evt.data);

                // TODO 消息号验证
                let msgid = dv.getUint16(0, true)

                // 包体
                let msgBody = evt.data.slice(2)

                let decoder = new TextDecoder('utf8')
                let jsonBody = decoder.decode(msgBody)

                // 解码包体
                let msg = JSON.parse(jsonBody)

                console.log( "Received Message: " , msg);


            }else{
                console.log("Require array buffer format")
            }

        };

        ws.onclose = function(evt) {
            console.log("Connection closed.");
        };
    }

</script>
</body>
</html>